const useDictStore = defineStore(
  'dict',
  {
    state: () => ({
      dict: new Array(),
      dictUpdater: {}
    }),
    persist: {
      enabled: false,
      strategies: [
        {
          key: 'dict',
          storage: window.localStorage
        }
      ]
    },
    actions: {
      setUpdater (key, updater = null) {
        if (!key || !updater || !updater instanceof Function) return
        if (!this.dictUpdater[key]) {
          this.dictUpdater[key] = [updater]
        } else {
          this.dictUpdater[key].push(updater)
        }
      },
      getUpdater (key) {
        if (!key) return
        return this.dictUpdater[key] || []
      },
      // 获取字典
      getDict (_key) {
        if (_key == null && _key == "") {
          return null;
        }
        try {
          for (let i = 0; i < this.dict.length; i++) {
            if (this.dict[i].key == _key) {
              return this.dict[i].value;
            }
          }
        } catch (e) {
          return null;
        }
      },
      // 设置字典
      setDict (_key, value, extra = {}) {
        if (_key !== null && _key !== "") {
          const item = {
            key: _key,
            value: value,
            ...extra
          }
          const index = this.dict.findIndex(i => i.key === _key)
          if (index === -1) {
            this.dict.push(item);
          } else {
            this.dict.splice(index, 1, item)
          }
        }
      },
      // 删除字典
      removeDict (_key) {
        return new Promise((resolve, reject) => {
          var bln = false;
          try {
            for (let i = 0; i < this.dict.length; i++) {
              if (this.dict[i].key == _key) {
                this.dict.splice(i, 1);
                resolve(true)
                return true;
              }
            }
          } catch (e) {
            bln = false;
          }
          resolve(false)
          return bln;
        })
      },
      // 清空字典
      cleanDict () {
        this.dict = new Array();
      },
      // 初始字典
      initDict () {
      }
    }
  })

export default useDictStore
